package cn.ctyun.ipush.web.controller;

import cn.ctyun.ipush.constant.ResultInfo;
import cn.ctyun.ipush.dto.ResultDto;
import cn.ctyun.ipush.model.LoginModel;
import cn.ctyun.ipush.utils.ConfigUtils;
import cn.ctyun.ipush.utils.DataUtils;
import cn.ctyun.ipush.utils.DateUtils;
import cn.ctyun.ipush.utils.MD5;
import cn.ctyun.ipush.web.user.bo.MenuTreeNode;
import cn.ctyun.ipush.web.user.bo.MenuUserNode;
import cn.ctyun.ipush.web.user.bo.UserModel;
import cn.ctyun.ipush.web.user.constanst.SessionAttributeKeys;
import cn.ctyun.ipush.web.user.service.MenuService;
import cn.ctyun.ipush.web.user.service.UserAdminService;
import com.dexcoder.commons.utils.UUIDUtils;
import com.dexcoder.dal.JdbcDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;


/**
 * Created with IntelliJ IDEA.
 * User: WJ
 * Date: 15-5-6
 * Time: 上午10:37
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Resource
    private UserAdminService userAdminService;
    @Resource
    private MenuService menuService;

    @Resource
    private JdbcDao jdbcDao;

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public ModelAndView userLogin(HttpServletRequest request) {
        return new ModelAndView("login", null);
    }

    @RequestMapping(value = "main", method = RequestMethod.GET)
    public String mainIndex(HttpServletRequest request, HttpSession session) {
        UserModel o = (UserModel) session.getAttribute("userInfo");
        if (o.getRole().equals("1")) {//营业员
            return "main";
        } else if (o.getRole().equals("2")) {//店长
            return "IB_DZ_MAIN";
        } else if (o.getRole().equals("3")) {//管理员
            return "IB_GLY_MAIN";
        }
        return null;
    }


    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ModelAndView userLoginCheck(HttpServletRequest request, HttpSession session) {
        String email = request.getParameter("email");
        String password = request.getParameter("password");

        UserModel systemUserModel = new UserModel();
        systemUserModel.setUserLoginName(email);
        systemUserModel.setUserPassword(password);
        logger.info("param is systemUser = {}", systemUserModel);
        if (systemUserModel == null) {
            //ModelAndView modelAndView = new ModelAndView();
            Map<String, Object> data = new HashMap<String, Object>();

            data.put("errorMsg", "未知错误，请联系管理员");

            return new ModelAndView("login", data);
        } else {
            if (systemUserModel.getUserLoginName() == null || systemUserModel.getUserLoginName().isEmpty()) {
                //throw new RuntimeException("loginUserName is empty");
                Map<String, Object> data = new HashMap<String, Object>();

                data.put("errorMsg", "用户名为空");

                return new ModelAndView("login", data);
            }
            if (systemUserModel.getUserPassword() == null || systemUserModel.getUserPassword().isEmpty()) {
                //throw new RuntimeException("userPassword is empty");
                Map<String, Object> data = new HashMap<String, Object>();

                data.put("errorMsg", "密码为空");

                return new ModelAndView("login", data);
            }
        }
        System.out.println(DataUtils.getFromBASE64(systemUserModel.getUserPassword()));
        systemUserModel = userAdminService.checkLogin(systemUserModel.getUserLoginName(), MD5.getMD5Code(DataUtils.getFromBASE64(systemUserModel.getUserPassword())));

        if (systemUserModel != null && systemUserModel.getUserModelId() != null) {
            //2000s不做操作就失效
            request.getSession().setAttribute(SessionAttributeKeys.SESSION_ATTR_KEY_USERINFO, systemUserModel);

            UserModel o = (UserModel) session.getAttribute("userInfo");
            if (o.getRole().equals("1")) {//营业员
                return new ModelAndView("main", null);
            } else if (o.getRole().equals("2")) {//店长
                return new ModelAndView("IB_DZ_MAIN", null);
            } else if (o.getRole().equals("3")) {//管理员
                return new ModelAndView("IB_GLY_MAIN", null);
            }

        } else {
            //throw new RuntimeException("用户或密码是错误的");
            //throw new RuntimeException("userPassword is empty");
            Map<String, Object> data = new HashMap<String, Object>();

            data.put("errorMsg", "用户名密码错误");

            return new ModelAndView("login", data);
        }
        return null;

    }

    /**
     * 捕获异常执行的方法
     *
     * @return
     */
    @ExceptionHandler(LoginException.class)
    @ResponseBody
    public ResultDto handlerException(Exception ex, HttpServletRequest req) {
        ResultDto resultDto = new ResultDto();
        resultDto.setInfo("用户名或密码错误").setStatus(ResultInfo.failure);
        return resultDto;
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public ModelAndView userLogout(HttpSession session, HttpServletRequest request) {
        if (session.getAttribute("userInfo") != null) {
            session.removeAttribute("userInfo");
        }
        return new ModelAndView("login", null);

    }


}
